/*
 * LoginInterceptor.java created on 2015-8-21. Copyright 2015 (C), Bozhong(Suzhou) Precision Industry Technology
 * Co.,Ltd. All rights reserved. No part of this material may be copied, reproduced, transmitted, stored in a retrieval
 * system, reverse engineered, decompiled, disassembled, localised, ported, adapted, varied, modified, reused,
 * customised or translated into any language in any form or by any means, electronic, mechanical, photocopying,
 * recording or otherwise, without the prior written permission of Bozhong(Suzhou) Precision Industry Technology
 * Co.,Ltd.
 */
package com.blog.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.blog.consts.AppConsts;
import com.blog.service.entity.User;
import com.blog.util.LogType;
import com.blog.util.LogUtil;

/**
 * 文件名： com.blog.interceptor.LoginInterceptor.java
 * 作者： WenBin
 * 日期： 2017年4月14日
 * 功能说明：
 * =========================================================
 * 修改记录：
 * 修改作者 日期 修改内容
 * =========================================================
 * Copyright (c) 2010-2011 .All rights reserved.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

	private static final String[] IGNORE_URL = { "/login", "/logout", "/checkLogin", "/static", "/code", "/article/out",
			"/bbs/out", "/demo/out", "/aboutme/out" };

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		boolean flag = true;
		String url = request.getRequestURL().toString();
		String contextPath = request.getContextPath();
		String actionUrl = url.substring(url.indexOf(contextPath) + contextPath.length());
		String requestType = request.getHeader("X-Requested-With");
		LogUtil.LOG(LogType.INFO, "请求类型：{}  访问路径：{}", requestType, actionUrl);
		for (String s : IGNORE_URL) {
			if (actionUrl.contains(s) || actionUrl.startsWith(s)) {
				LogUtil.LOG(LogType.INFO, "该路径是无需验证的路径:{}", actionUrl);
				flag = false;
				break;
			}
		}
		if (flag) {
			request.getSession().setAttribute(AppConsts.LAST_PAGE, actionUrl);
			User user = (User) request.getSession().getAttribute(AppConsts.USER_INFO);
			if (user == null) {
				response.sendRedirect(request.getContextPath() + "/login/backLogin");
				return false;
			}
		}
		// response.sendRedirect(request.getContextPath() + "/login/backLogin");
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

		super.postHandle(request, response, handler, modelAndView);
	}
}
